﻿// widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QDebug>
#include <QCamera>
#include <QCameraInfo>
#include <QVideoFrame>
#include <QImage>
#include <QPixmap>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // Set background color for the main widget
    setStyleSheet("background-color: #2b2b2b; color: white;");

    // Create serial port object
    serial = new QSerialPort(this);

    // Create status bar label
    statusLabel = new QLabel(this);
    statusLabel->setText("Status: Serial port not open");
    statusLabel->setAlignment(Qt::AlignCenter);
    statusLabel->setStyleSheet("background-color: #444444; padding: 5px; border-radius: 3px;");

    // Create face label with black background
    faceLabel = new QLabel(this);
    faceLabel->setStyleSheet("background-color: black; color: white; border: 2px solid white; border-radius: 5px;");
    faceLabel->setAlignment(Qt::AlignCenter);
    faceLabel->setText("Initializing Camera..."); // Initial text
    faceLabel->setMinimumHeight(100); // Set a minimum height for visibility

    // Create UI buttons with styling
    QPushButton *btnOn = new QPushButton("RESET", this);
    btnOn->setStyleSheet(buttonStyle());
    QPushButton *btnOff = new QPushButton("Claw Small", this);
    btnOff->setStyleSheet(buttonStyle());
    QPushButton *btnOff2 = new QPushButton("Claw Large", this);
    btnOff2->setStyleSheet(buttonStyle());

    // Create grid layout
    QGridLayout *gridLayout = new QGridLayout(this);

    // Add widgets to the grid
    gridLayout->addWidget(faceLabel, 0, 0, 1, 3); // faceLabel spans all 3 columns
    gridLayout->addWidget(btnOn, 1, 0);
    gridLayout->addWidget(btnOff, 1, 1);
    gridLayout->addWidget(btnOff2, 1, 2);
    gridLayout->addWidget(statusLabel, 2, 0, 1, 3); // statusLabel spans all 3 columns

    // Set the grid layout for the widget
    setLayout(gridLayout);

    // Connect signals and slots
    connect(btnOn, &QPushButton::clicked, this, [this]() { sendCommand("#255P1500T2000!", "RESET"); });
    connect(btnOff, &QPushButton::clicked, this, [this]() { sendCommand("#005P1000T1000!", "Claw Small"); });
    connect(btnOff2, &QPushButton::clicked, this, [this]() { sendCommand("#005P1500T1000!", "Claw Large"); });

    // Open serial port
    serial->setPortName("COM4");  // Replace with your actual serial port
    serial->setBaudRate(QSerialPort::Baud115200);
    if (!serial->open(QIODevice::ReadWrite)) {
        QMessageBox::warning(this, "Error", "Could not open serial port! Please check the connection.");
        statusLabel->setText("Status: Could not open serial port");
        qDebug() << "Failed to open port";
    } else {
        statusLabel->setText("Status: Serial port opened");
        qDebug() << "Serial port opened successfully";
    }

    // Initialize camera
    initCamera();
}

Widget::~Widget()
{
    delete ui;
    if (serial->isOpen()) {
        serial->close();
        qDebug() << "Serial port closed";
    }
    if (camera) {
        camera->stop();
        delete camera;
    }
}

void Widget::sendCommand(const QString &cmd, const QString &action) {
    if (serial->isOpen()) {
        serial->write(cmd.toUtf8());
        statusLabel->setText("Status: " + action + " command sent");
        qDebug() << action << " command sent: " << cmd;
    } else {
        QMessageBox::warning(this, "Error", "Serial port not open, cannot send command");
        statusLabel->setText("Status: Serial port not open");
        qDebug() << "Failed to send command, serial port not open";
    }
}

QString Widget::buttonStyle() {
    return "QPushButton {"
           "    background-color: #555555;"
           "    color: white;"
           "    border-style: outset;"
           "    border-width: 2px;"
           "    border-radius: 5px;"
           "    border-color: #777777;"
           "    padding: 6px;"
           "}"
           "QPushButton:hover {"
           "    background-color: #777777;"
           "}"
           "QPushButton:pressed {"
           "    background-color: #333333;"
           "    border-color: #555555;"
           "}";
}

void Widget::initCamera()
{
    QList<QCameraInfo> availableCameras = QCameraInfo::availableCameras();
    if (availableCameras.count() > 1) {
        // Use the second camera (index 1) if available
        camera = new QCamera(availableCameras.at(1));
    } else if (availableCameras.count() > 0) {
        // Fallback to the first camera if only one is available
        camera = new QCamera(availableCameras.at(0));
        qDebug() << "Using the first available camera.";
    } else {
        QMessageBox::warning(this, "Error", "No camera devices found!");
        faceLabel->setText("No Camera Found");
        return;
    }

    connect(camera, &QCamera::readyForCaptureChanged, this, &Widget::readyForCapture);
    connect(camera, &QCamera::errorOccurred, this, &Widget::displayCameraError);

    imageCapture = new QImageCapture(camera, this);
    connect(imageCapture, &QImageCapture::imageCaptured, this, &Widget::processCapturedImage);

    camera->start();
}

void Widget::readyForCapture(bool ready)
{
    if (ready) {
        // Optionally, you can trigger capture here if needed
        // imageCapture->capture();
    }
}

void Widget::processCapturedImage(int id, const QImage& preview)
{
    Q_UNUSED(id);
    // Display the captured image on the faceLabel
    QPixmap pixmap = QPixmap::fromImage(preview.scaled(faceLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
    faceLabel->setPixmap(pixmap);
    faceLabel->setText(""); // Clear the "Initializing Camera..." text
}

void Widget::displayCameraError(QCamera::Error error)
{
    QMessageBox::warning(this, "Camera Error", camera->errorString());
    faceLabel->setText("Camera Error");
}

void Widget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    // Update the camera preview size when the widget is resized
    if (imageCapture && imageCapture->isReadyForCapture()) {
        // You might need to re-trigger a capture to update the displayed image size
        // or handle resizing dynamically if your camera supports it.
    }
}
